<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/27
 * Time: 14:40
 */

namespace App\Api\Admin\Controllers;


use App\Exceptions\ApiException;
use Illuminate\Http\Request;
use App\Models\Admin\AdminUser;
use App\Models\Shareholder;
use App\Models\ShareholderLog;
use App\Models\Admin\Log;
use App\Models\MemberShip;
use  App\Models\User;
use  Excel;

class ManageController extends CommonController
{
    public function __construct()
    {
        parent::__construct();
        if ($this->user['permissions'] !== '*' && !isset($this->user['permissions']['user'])) {
            throw new ApiException('没有权限', 0);
        }
    }

    public function index(Request $request)
    {
        $page = intval($request->input('page')) ?: 1;
        $name = IT('name');
        $page = $page - 1;
        $pageSize = 10;
        $where = [];
        if ($name) {
            $where[] = ['username', 'like', '%' . $name . '%'];
        }
        if ($this->user['permissions'] == '*') {
            $user_list = AdminUser::where($where)->skip($page * $pageSize)->take($pageSize)->orderBy('id', 'desc')->get();
        } else {
            throw new ApiException('没有权限', 0);
        }
        return json_success('ok', $user_list);
    }

    /**
     * 添加管理员
     * @param Request $request
     * @return array
     */
    public function AddUser()
    {
        $username = IT('username', true, '亲填写用户名');
        $pasword = IT('password', true, '请填写密码');
        $role_id = IT('role_id', true, '请选择用户的角色');
        $avatar = IT('avatar');
        $data = [
            'username' => $username,
            'password' => MD5($pasword),
            'role_id' => $role_id,
            'name' => $username,
            'avatar' => $avatar,
            'encrypt' => str_random(8),
            'created_at' => time2date(),
        ];
        if ($this->user['permissions'] == '*') {
            $id = AdminUser::insertGetId($data);
            if ($id) {
                (new Log)->add($this->user, '添加用户' . $username . ', id为' . $id . '');
                return json_success('ok');
            } else {
                return json_error('添加用户失败');
            }
        } else {
            throw new ApiException('没有权限添加用户', 0);
        }
    }

    /**
     * 修改管理员名称和密码
     * @param Request $request
     * @return array
     */

    public function ModifyUser()
    {
        $user_id = IT('id', true, '请填写用户ID');
        $username = IT('username');
        $password = IT('password');
        $role_id = IT('role_id');
        $modifuser = AdminUser::find($user_id);
        if(!$modifuser){
            return json_error('该用户不存在');
        }
        if(!empty($username) && $username!== $modifuser->username){
            $modifydata['username'] = $username;
            $modifydata['name'] = $username;
        }
        if(!empty($password) && MD5($password) !==$modifuser->username ){
            $modifydata['password'] = MD5($password);
        }
        if(!empty($role_id) && $role_id!==$modifuser->role_id){
            $modifydata['role_id'] = $role_id;
        }
        $modifydata['encrypt'] =  str_random(8);
        $modifydata['updated_at'] = time2date();
        if ($this->user['permissions'] == '*') {
            if ($modifuser) {
                $user = $modifuser->update($modifydata);
                if ($user) {
                    (new Log)->add($this->user, '修改了管理员' . $username . ', id为' . $user_id . '');
                    return json_success('ok');
                } else {
                    return json_error('修改失败');
                }
            }
        } else {
            throw new ApiException('你没有权限修改', 0);
        }
    }
  /**
   *股东用户列表
   *
   */
     public function AdminShareholderList(Request $request){
         $TotalStock = config('admin.TotalStock');//总注册资金
         $page = intval($request->input('page')) ?: 1;
         $mobile = IT('mobile');
         $page = $page - 1;
         $pageSize = IT('pagesize') ?: 10;
         $where = [];
         if ($mobile) {
             $where[] = ['mobile', 'like', '%' . $mobile . '%'];
         }
         $total = Shareholder::where($where)->where('status','=',0)->count();
         $totalPage = ceil($total / $pageSize);
         $lists = Shareholder::where($where)->where('status','=',0)->skip($page * $pageSize)->take($pageSize)->orderBy('id', 'desc')->get(['id','user_name','share','sex','mobile','Birthday','created_at','updated_at','total_funds','certificate_number']);
         foreach ($lists as &$key) {
            $key->ratio  = $key->share/$TotalStock;
         }
         unset($key);
         return json_success('ok',['total'=>$total,'totalPage' => $totalPage, 'list' => $lists]);
     }
    /**
     * 股东用户导出excel
     *
     */
    public function ShareholderExport(){
        $TotalStock = config('admin.TotalStock');//总注册资金
        $Shareholder_data = Shareholder::where('status','=',0)->select('user_name','sex','Birthday','mobile','share','total_funds','created_at','certificate_number')->get();
        foreach($Shareholder_data as $k){
            $k->ratio= $k->share/$TotalStock;
        }
        (new Log)->add($this->user, '导出了股东excel表格');
        return json_success('ok',$Shareholder_data);
      /*
        $export_arr = array();
            $export_arr[0]['name'] = trans("Shareholder.Shareholder.name");
            $export_arr[0]['sex'] = trans("Shareholder.Shareholder.sex");
            $export_arr[0]['Birthday'] = trans("Shareholder.Shareholder.Birthday");
            $export_arr[0]['mobile'] = trans("Shareholder.Shareholder.mobile");
            $export_arr[0]['share'] = trans("Shareholder.Shareholder.share");
            $export_arr[0]['total_funds'] = trans("Shareholder.Shareholder.total_funds");
            $export_arr[0]['ratio'] = trans("Shareholder.Shareholder.filter_placeholder");
            $export_arr[0]['created_at'] = trans("Shareholder.Shareholder.created_at");
            $export_arr[0]['certificate_number'] = trans("Shareholder.Shareholder.certificate_number");
            foreach($Shareholder_data as $key=>$val) {
                $export_arr[$key + 1]['name'] = $val->user_name;
                $export_arr[$key + 1]['sex'] = $val->sex;
                $export_arr[$key + 1]['Birthday'] = $val->Birthday;
                $export_arr[$key + 1]['mobile'] = $val->mobile;
                $export_arr[$key + 1]['share'] = $val->share;
                $export_arr[$key + 1]['total_funds'] = $val->total_funds;
                $export_arr[$key + 1]['ratio']=  $val->share/$TotalStock;
                $export_arr[$key + 1]['created_at']=  $val->created_at;
                $export_arr[$key + 1]['certificate_number']=  $val->certificate_number;
            }
          Excel::create(trans("Shareholder.shareholder_title"), function($excel) use ($export_arr){
                $excel->sheet(trans("Shareholder.shareholder_title"), function($sheet) use ($export_arr){
                    $sheet->setWidth(['A'=>20, 'B'=>20,'C'=>20, 'D'=>20,'E'=>20,'F'=>20, 'G'=>20, 'H'=>20, 'I'=>20,]);
                    $sheet->rows($export_arr);
                });
            })->export('xls');*/
        }

    /**
     * @return array
     * 会员数据导出
     */
     public function MembershipExport(){
         $list= MemberShip::where('status',0)->select('name','mobile','number','sex','admission_fee','bank_number')->get();
       /*  foreach($list as $k){
             $k->user_name = $k->name;
             unset($k->name);
         }*/
            (new Log)->add($this->user, '导出了会员excel表格');
            return json_success('ok',$list);
        }

    /**
     * 股东详情
     * @return array
     */
     public function SingleShareholder(){
         $TotalStock = config('admin.TotalStock');//总注册资金
         $id = IT('id',true,'请输入用户id');
         $data = Shareholder::where('id','=',$id)->first();
         $data->ratio = $data['share']/$TotalStock;
         return json_success('ok', $data);
     }
     /**
      *股东信息修改
      *
      */
     public function EditShareholder()
    {
        $id = IT('id', true, '请输入ID');
        $user_name = IT('user_name');
        $sex = IT('sex');
        $share = IT('share');
        $mobile = IT('mobile');
        $Birthday = IT('Birthday');
        if (!empty($user_name)) {
            $Shareholder_data['user_name'] = $user_name;
        }
        if (!empty($sex)) {
            $Shareholder_data['sex'] = $sex;
        }
        $Shareholder_info = Shareholder::where('id', '=', $id)->first();

        //认购份额改表，写入股东信息变更记录
        if (!empty($share)) {
            $dilution = (int)$share - (int)$Shareholder_info->shar;
            $Surplus = (int)$Shareholder_info->share - (int)$share;
            $insert_data = [
                'shareholder_id' => $Shareholder_info->id,
                'total_number' => $Shareholder_info->share,
                'dilution' => $dilution,
                'Surplus' => $Surplus,
                'time' => time2date(),
            ];
           $upda= Shareholder::where('id', '=', $id)->update(['share'=>$share,'updated_at'=>time2date()]);
           if($upda  && $share!== $Shareholder_info->share){
               //将信息，写入到股权变更日志表
               ShareholderLog::insert($insert_data);
           }
        }
        if (!empty($mobile)) {
            if (!preg_match("/^\\d{11}$/", $mobile)) {
                return json_error('手机号必须为11位数字');
            }
            $Shareholder_data['mobile'] = $mobile;
        }
        if (!empty($Birthday)) {
            $Shareholder_data['Birthday'] = $Birthday;
        }
        $Shareholder_data['updated_at'] = time2date();
        $Shareholder_update = Shareholder::where('id', '=', $id)->update($Shareholder_data);
        if ($Shareholder_update) {
            // 如果修改手机号 ：旧手机号
            if($mobile != $Shareholder_info->mobile){
                $userRows = User::where([['mobile', '=', $Shareholder_info->mobile]])->first();
                if(!empty($userRows) && $userRows->role == 1)
                    User::where('mobile', '=', $Shareholder_info->mobile)->Update(['role' => 0]);
            }
            // 如果修改手机号 ：旧手机号
            $userRows = User::where([['mobile', '=', $mobile]])->first();
            if(!empty($userRows) && $userRows->role != '1')
                User::where('mobile', '=', $mobile)->Update(['role' => 1]);
            (new Log)->add($this->user, '修改了股东' . $user_name . ',的信息-股东id为' . $id . '');
             return json_success('ok');
        }elseif(empty($Shareholder_update)){
              return json_error('请填写你要修改的内容');
        }else{
            return json_error('修改失败');
        }
    }
    /**
     * 添加股东
     * @return array
     * @throws \Exception
     *
     */
     public function AddShareholder(){
         $user_name = IT('user_name',true,'请输入用户名');
         $sex = IT('sex',true,'请输入性别');
         $share = IT('share',true,'请输入认购金额');
         $mobile = IT('mobile',true,'请输入手机号码');
         $Birthday = IT('Birthday',true,'请输入生日');
         $total_funds = IT('total_funds',true,'请输入总钱数');
         $certificate_number = IT('certificate_number',true,'请输入证书编号');
         $check_mobile = Shareholder::where('mobile','=',$mobile)->first();
         if($check_mobile){
           return json_error('手机号已存在');
         }
         if(!preg_match("/^\\d{11}$/",$mobile)){
             return  json_error('手机号必须为11位数字');
         }
         if(!is_numeric($share)){
             return json_error('你的认购份额不是数字类型');
         }
         $data =[
             'user_name'=> $user_name,
             'share'=> $share,
             'mobile'=> $mobile,
             'sex' => $sex,
             'Birthday' => $Birthday,
             'total_funds' => $total_funds,
             'certificate_number' => $certificate_number,
             'created_at' => time2date(),
         ];
         $data= Shareholder::insert($data);
         if($data){
             //Todo 股东添加成功的话，users表中存在该用户的话则修改为股东
              User::where('mobile','=',$mobile)->Update(['role'=>1]);
             (new Log)->add($this->user, '添加了股东，姓名-' . $user_name );
             return json_success('ok');
         }else{
             return  json_error('添加失败');
         }
     }

    /**
     * 股东删除
     * @return array
     *
     */
     public function DelShareholder(){
         $id= IT('id',true,'请输入id');
         $user_data = Shareholder::where('id','=',$id)->first();
         $update_data = Shareholder::where('id','=',$id)->update(['status'=> 1]);
         if($update_data){
             User::where('mobile','=',$user_data->mobile)->Update(['role'=> 0]);
             (new Log)->add($this->user, '删除了股东，id-' . $id );
             return json_success('ok');
         }else{
             return json_error('删除失败');
         }
     }

    /**
     * @param Request $request
     * @return array
     * 股金变更日志
     */
     public function ShareholderLgo(Request $request){
         $id= IT('id',true,'请输入id');
         $page = intval($request->input('page')) ?: 1;
         $page = $page - 1;
         $pageSize = IT('pagesize') ?: 10;
         $data = ShareholderLog::where('shareholder_id','=',$id)->skip($page * $pageSize)->take($pageSize)->orderBy('id', 'desc')->get();
         return json_success('ok',$data);
     }
    /**
     * @return array
     * 总注册资金
     */
     public function RegisteredCapital(){
         $data = config('admin.TotalStock');//总注册资金
         return json_success('ok',$data);
     }

    /**
     *推广会员列表
     *
     */
     public function MembershipList(Request $request){
         $page = intval($request->input('page')) ?: 1;
         $page = $page - 1;
         $pageSize = IT('pagesize') ?: 10;
         $name = $request->input('name');
         $mobile = $request->input('mobile');
         $where=[];
         if (isset($name)) {
             $where[] = ['name', 'like', '%' . $name . '%'];
         }elseif(isset($mobile)){
             $where[] = ['mobile', 'like', '%' . $mobile . '%'];
         }
         $total =  MemberShip::where($where)->where('status','=',0)->count();
         $totalPage = ceil($total / $pageSize);
         $menber = MemberShip::where($where)->where('status','=',0)->skip($page * $pageSize)->take($pageSize)->orderBy('id', 'desc')->get(['id','name','mobile','number','avatar','sex','bank_number','admission_fee','term_validity','created_at']);
         foreach ($menber as $k){
             $k->menber_type = "推广会员";
             $k->created_at = !empty($k->created_at) ? substr($k->created_at,0,10) : '';
         }
         unset($k);
         return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $menber]);
     }

    /**
     * @return array
     * 添加会员
     */
     public function  AddMember(){
         $name = IT('name',true,'亲输入姓名');
         $sex = IT('sex');
         $mobile = IT('mobile',true,'请输入手机号码');
         $number = IT('number',true,'请输入会员编号');
         $admission_fee = IT('admission_fee');
         $time_admission = IT('time_admission',true,'请输入入会时间');
         $bank_number = IT('bank_number');
         $term_validity = IT('term_validity');
         $member_data = MemberShip::where(['mobile'=>$mobile ,'stutas'=> 0])->first();
         if($member_data){
              return json_error('手机号码已存在');
         }
         $data = [
             'name' =>$name,
             'mobile' =>$mobile,
             'number' =>$number,
             'sex' =>$sex,
             'bank_number' =>$bank_number,
             'admission_fee' =>$admission_fee,
             'term_validity' =>$term_validity,
             'created_at' => $time_admission
         ];
         $insert_date = MemberShip::insertGetId($data);
         if($insert_date){
                 //TODO 添加成功，修改users 表中的会员状态
                 User::where('mobile','=',$mobile)->update(['membership'=>1]);
                (new Log)->add($this->user, '添加了推广会员，id为-' . $insert_date );
                return json_success('ok');
         }else{
             return json_error('添加失败!');
         }
     }

    /**
     * @return array
     * 推广会员详情
     */
     public function MembereDtails(){
         $id=IT('id',true,'请输入ID');
         $data= MemberShip::where('id','=',$id)->first(['id','name','mobile','sex','number','avatar','bank_number','admission_fee','created_at','term_validity']);
         return json_success('ok',$data);
     }
    /**
     * @return array
     * 推广会员修改
     */

     public function EditMember(){
        $id = IT('id',true,'请输入会员ID');
        $check_user = MemberShip::where('id','=',$id)->first();
        if(!$check_user){
            return json_error('暂无此用户');
        }
         $name = IT('name');
         $sex = IT('sex');
         $mobile = IT('mobile');
         $number = IT('number');
         $admission_fee = IT('admission_fee');
         $time_admission = IT('time_admission');
         $bank_number = IT('bank_number');
         $term_validity = IT('term_validity');
         if(!preg_match("/^\\d{11}$/",!empty($mobile))){
             return json_error('手机号必须为11位数字');
         }
         if(!is_numeric(!empty($number))){
             return json_error('请检查你的会员编号类型是否正确');
         }
         if(!is_numeric(!empty($bank_number))){
             return json_error('请检查你的银行卡类型是否正确');
         }
         if($name!== $check_user->name){
           $update_user['name'] = $name ;
         }
         if($sex !== $check_user->sex){
             $update_user['sex']=$sex;
         }
         if($mobile !== $check_user->mobile){
             $update_user['mobile']=$mobile;
         }
         if($number!== $check_user->number){
             $update_user['number']=$number;
         }
         if($admission_fee!== $check_user->admission_fee){
             $update_user['admission_fee']=$admission_fee;
         }
         if($time_admission !== $check_user->time_admission){
             $update_user['created_at']=$time_admission;
         }
         if($bank_number!== $check_user->bank_number){
             $update_user['bank_number']=$bank_number;
         }

         if($term_validity!== $check_user->term_validity){
             $update_user['term_validity']=$term_validity;
         }
          $success_data =MemberShip::where('id','=',$id)->update($update_user);
         if($success_data){
             (new Log)->add($this->user, '修改推广会员，id为-' . $id );
             return json_success('ok');
         }elseif(empty($success_data)){
             return json_error('请填写，你要修改的内容');
         }else{
             return json_error('修改失败');
         }
     }

    /**
     * 推广会员删除
     */
     public function DelMember(){
         $id = IT('id',true,'请输入ID');
         $member_data = MemberShip::where('id','=',$id)->first();
         if(!$member_data){
              return json_error('此会员不存在');
         }
         $del_date = MemberShip::where('id','=',$id)->update(['status'=>1]);
         if($del_date){
             //TODO 删除成功，修改users 表中的会员状态
             User::where('mobile','=',$member_data->mobile)->update(['membership'=> 0]);
             (new Log)->add($this->user, '删除了推广会员，id为-' .$id );
             return json_success('ok');
         }else{
            return json_error('删除失败');
         }
     }



     
}